#-*- coding:utf8 -*-
"""
Function attributes:
* load: boolean. Optional. If False the function will not load.
* name: string. Optional.
* priority: string. Optional. Three values are available: "high", "medium" or "low",
  default value: "medium".
* thread: boolean. Optional. If True, function will work by starting a thread.
* rule: string or regexp object. Required.
* aliases: list of string or regexp objects. Optional.
* fullmsg: boolean. Optional. If True, pattern is searched on whole message, else
  pattern is a command, the message must begin with a sign.

* access
* evttypes: must be tuple
* limit
* channels
* url
* showas
"""

import re
from util.functions import *
from core.optimizers import fmt
from util.xplor import Xplorer
from util.pywikilib import WikiLink, Site, Page

field = "words"

clean_tags = lambda x: re.sub("<.*?>(.*?)<.*?>", r"\1", x)
clean_sp = lambda x: re.sub("( ) +", r"\1", x)
clean = lambda x: clean_sp(clean_tags(x)).strip()

html_entities = {
	"aacute": u"á",
	"agrave": u"à",
	"ccedil": u"ç",
	"eacute": u"é",
	"egrave": u"è",
	"iacute": u"í",
	"iuml": u"ï",
	"oacute": u"ó",
	"ograve": u"ò",
	"uacute": u"ú",
	"uuml": u"ü",
	"#156": u"œ",
	"#x2192": u"→", #;&nbsp; 
	"nbsp": " "
}

def swap(string, enc=None):
	if enc:
		string = string.decode(enc)
	for name, value in html_entities.iteritems():
		upcase = name.title()
		string = string.replace("&%s;" % name, value)
		string = string.replace("&%s;" % upcase, value.upper())
	return string

def drae(bot, evt, cmd):
	word = cmd.arguments
	num = int(cmd.opts['a']) if cmd.opts['a'] and cmd.opts['a'].isdigit() else 1
	num-=1
	if not word: return
	rtn = "http://rae.es/%s" % word
	info, html = Xplorer.get_url(drae.url % word, {"accept-encoding":"identity"})
	if "<TITLE>RAE. DRAE. Aviso de error.</TITLE>" in html:
		bot.reply(evt, u"word &B;%s&N; doesn't exist", word)
		return True
	defs = re.search("<div>(.*)</div>", html.decode("utf8")).group(1)

	meanings = re.findall('<p style="margin-left:.em; margin-bottom:-0.5em">(.*?)</p>', defs)
	ethym = clean(meanings[1])
	senses = meanings[3:]
	meanings = []
	for meaning in  senses:
		meaning = clean(meaning).strip()
		if "~" in meaning: break
		if not meaning:
			continue
		meaning = meaning.replace("</span>","")
		meanings.append(meaning.strip())
	if num>len(meanings):num=len(meanings)
	bot.reply(evt, u"&B;%s:&N; %s %s [%s meanigs matched] | %s", word, ethym, meanings[num], len(meanings), rtn)
drae.rule = "drae"
drae.url = "http://buscon.rae.es/draeI/SrvltGUIBusUsual?LEMA=%s"

def dpd(bot, evt, cmd):
	word = cmd.arguments
	num = int(cmd.opts['a']) if cmd.opts['a'] and cmd.opts['a'].isdigit() else 1
	num-=1
	if not word: return
	rtn = dpd.url % word
	info, html = Xplorer.get_url(dpd.url % word, {"accept-encoding":"identity"})
	if "</b></i> no est&#x00E1; registrada en el <i>DPD</i>. Las que se muestran a continuaci&#x00F3;n tienen una escritura cercana.</p>" in html:
		bot.reply(evt, u"word &B;%s&N; doesn't exist", word)
		return True
	descr = re.search("<!--/lema-->. </span>(.*?)(</[ap]>)?<ESTADO_BIEN/>", html.decode("iso-8859-1")).group(1)
	descr= swap(clean(descr))
	bot.reply(evt, u"&B;%s:&N; %s | %s", word, descr, rtn)
dpd.rule = "dpd"
dpd.url = "http://buscon.rae.es/dpdI/SrvltGUIBusDPD?lema=%s"

def diec(bot, evt, cmd):
	""".diec <mot> [-a #] - retorna la primera definició del mot. Amb -a #, on # és un nombre, retorna la definició desitjada"""
	if not cmd.arguments: return
	u"""
	&operEntrada=0 Coincident
	&operEntrada=1 Començada per
	&operEntrada=2 Acabada per
	&operEntrada=3" En qualsevol posició
	&operEntrada=4 No començada per
	&operEntrada=5 No acabada per
	&operEntrada=6 Que no contingui
	"""
	word = cmd.arguments
	num = int(cmd.opts['a']) if cmd.opts['a'] and cmd.opts['a'].isdigit() else 1
	num-=1
	info, html = Xplorer.get_url(diec.url % quote(word, "ISO-8859-1"), {"accept-encoding":"identity"})
	txt = re.search("<h2>(.*?)</tr></table>", html.decode("ISO-8859-1"))

	items = clean(txt.group(1).replace("<br />","[br/]").replace("&#8217;","'")).split("[br/]")
	i=0
	senses = []

	ortho = items[0]
	for item in items[2:]:
		i+=1
		s = re.sub("\d( \d*)??" , "", item).strip()
		senses.append("%i %s %s"%(i,s,diec.url % quote(word, "ISO-8859-1")))
		print i, s
	try:
		bot.reply(evt, "&B;%s&N;: %s" %(ortho,senses[num]))
	except IndexError:
		bot.reply(evt, "&r;%s&N; no existeix. %s" % (word, diec.url % quote(word, "ISO-8859-1")))
diec.rule = "diec"
diec.url = "http://dlc.iec.cat/results.asp?txtEntrada=%s"

def trads(bot, evt, cmd):
	word = cmd.dict['word']
	if word:
		lang = {"es": "b", "fr": "c", "en": "d", "de": "e"}[cmd.dict['lang']]
		info, html = Xplorer.get_request(trads.url % (lang, quote(word, "ISO-8859-1")), {"accept-encoding":"identity"})
		print info
		txt = re.search("(?s)<TABLE CELLPADDING=0 CELLSPACING=0 BORDER=0 WIDTH=100%>(.*?)</TABLE>", html).group(1)
		txt = re.sub("<script>(.*?)</script>","", txt)
		txt = re.sub("&nbsp;", "\n", txt)
		txt = re.sub("(?i)<b>(.*?)</b>", r"&B;\1&N;", txt)
		txt = re.sub("(?i)<v>(.*?)</v>", r"&l;\1&N;", txt)
		txt = re.sub('(?i)<a href="[^"]+">(.+?)</a>', r"&U;\1&N;", txt)
		txt = clean(txt)
		txt = swap(txt, "ISO-8859-1")
		txt = txt.splitlines()[2]

		bot.reply(evt, txt)
trads.rule = re.compile(r"^(?:$both)(?P<lang>es|fr|en|de)-ca (?P<word>.+)")
trads.fullmsg = True
trads.url = "http://www.grec.net/cgibin/mlt003c.pgm?CBD=%s&GECART=%s"
trads.def_url= "http://www.grec.net/cgibin/mlt003c.pgm?CBD=d&GECART=%s"

def catrads(bot, evt, cmd):
	if not cmd.arguments: return
	word = cmd.dict['word']
	info, html = Xplorer.get_request(catrads.url % quote(word), {"accept-encoding":"identity"})
	#txt = re.sub("> *<",">\n<", html)
	txt = re.search("(?s)<TABLE CELLPADDING=0 CELLSPACING=0 width=100%>(.*?)</TABLE>", html).group(1)
	txt = re.sub("(?i)<br><br>", "| ", txt)
	txt = re.sub("</td>", "",txt)
	txt = re.sub("<script>(.*?)</script>","", txt)
	txt = re.sub("(?ism)<b>(.*?)</b>", r"&B;\1&N;", txt)
	txt = re.sub("(?ism)<i>(.*?)</i>", r"&+g;\1&N;", txt)
	txt = re.sub("(?ism)<i>(.*?)</i>", r"", txt)
	txt = txt.replace(" | </P>","")
	txt = swap(txt, "windows-1252")
	txt = clean(txt)
	data = [x.split(": &N;") for x in txt.split("| ") if ": &N;" in x]
	langs = {
		"es": u"castellà",
		"fr": u"francés",
		"en": u"anglés",
		"de": "alemany",
		u"Castellà": "es",
		u"Francès": "fr",
		u"Anglès": "en",
		"Alemany": "de"
	}
	voc = {u"es":[], u"fr": [], u"en":[], "de": []}
	for k, v in data:
		if langs[k[3:]] not in voc:continue
		voc[langs[k[3:]]].append(v)

	print "\n\n\n",voc,"\n\n\n"
	lang = cmd.dict['lang']
	if lang=="*":
		txt = " | ".join(["&B;%s&N;: %s" % (langs[k],"; ".join(v)) for k, v in voc.iteritems()])
	else:
		txt = "&B;%s&N;: %s"  % (langs[lang], "; ".join(voc[lang]))
	bot.reply(evt, txt)
catrads.rule = re.compile(r"^(?:$both)ca-(?P<lang>\*|es|fr|en|de) (?P<word>.+)")
catrads.fullmsg = True
catrads.url = "http://www.grec.cat/cgibin/mlt00x.pgm?GECART=%s"
